'''
处理非实时数据,尽可能的减少API的调用

例如日出——日落时间
'''

import requests
import json
import time
import os
from logging import *

from .config import *
from .rainmeter import *

from lib.parse_time import *

def run():
    basicConfig(
        level=0,
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        filename="log",
        filemode="a",
        encoding='UTF-8'
    )

    out = Rainmeter()

    target_id = out["ID"]

    try:
        data = requests.get(f"https://devapi.qweather.com/v7/astronomy/sun?key={key}&location={target_id}&date={format('%Y%m%d')}")
        data = data.content.decode("UTF-8")
        data = json.loads(data)
        data['updateTime'] = reformat(data['updateTime'])
    except requests.ConnectionError:
        error(f"Disconnected from Internet")
        with open("temp/lock", 'w') as f:
            f.write('null')
        info("quit...")
        out.save()
        return
    except KeyError:
        error(f"An Error caused while getting fresh. Detail: {data}")
        with open("temp/lock", 'w') as f:
            f.write('null')
        info("quit...")
        out.save()
        return

    info("Succeed Got Refreshed Data")

    try:
        data["sunrise"] = format("%H:%M:%S", reformat(data["sunrise"]))
        data["sunset"] = format("%H:%M:%S", reformat(data["sunset"]))
    except:
        ...

    out["sunrise"] = data["sunrise"]
    out["sunset"] = data["sunset"]

    info("quit...")